//
//  HttpNetworkManager.m
//  Maylida
//
//  Created by Laojingxing on 2018/4/16.
//  Copyright © 2018年 laojingxing. All rights reserved.
//

#import "HttpNetworkManager.h"

@implementation HttpNetworkManager

DEFINE_SINGLETON_IMPLEMENTATION(HttpNetworkManager);

- (instancetype)init
{
    self = [super init];
    if (self) {
        self.allTaskArray = [NSMutableArray array];
    }
    return self;
}

- (void)postRequestWithUrl:(NSString *)urlString parameters:(NSDictionary *)parameters successBlock:(SuccessBlock)successBlock failureBlock:(FailureBlock)failureBlock {
    [self postWithUrl:urlString parameters:parameters successBlock:^(id task, id responseObject) {
        // 处理数据
        [self dealData:responseObject task:task success:successBlock failure:failureBlock];
    } failureBlock:^(id task, NSError *error) {
        failureBlock(task, error);
    }];
}

- (void)postWithUrl:(NSString *)urlString parameters:(NSDictionary *)parameters successBlock:(SuccessBlock)successBlock failureBlock:(FailureBlock)failureBlock {
    // 设置请求头
    [self.requestManager.requestSerializer setValue:@"laojingxing" forHTTPHeaderField:@"name"];
    
    // 发送请求
    NSURLSessionDataTask *task = [self.requestManager POST:urlString parameters:parameters progress:^(NSProgress * _Nonnull uploadProgress) {
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        successBlock(task, responseObject);
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        failureBlock(task, error);
    }];
    
    [self.allTaskArray addObject:task];
}

#pragma mark - deal Data
- (void)dealData:(id)responseObject
            task:(id)task
         success:(SuccessBlock)success
         failure:(FailureBlock)failure {
    if ([responseObject isKindOfClass:[NSData class]]) {
        // 判断返回的数据是不是NSData，如果是的话，那就转成集合形式
        id responseData = [NSJSONSerialization JSONObjectWithData:responseObject options:(NSJSONReadingMutableContainers) error:nil];
        if (responseData == nil) {
            responseData = [[NSString alloc] initWithData:responseObject encoding:NSUTF8StringEncoding];
        }
        success(task, responseData);
    } else {
        success(task, responseObject);
    }
}

#pragma mark - Getter && Setter
- (AFHTTPSessionManager *)requestManager {
    if (_requestManager == nil) {
        _requestManager = [AFHTTPSessionManager manager];
        //设置相应内容类型
        _requestManager.responseSerializer.acceptableContentTypes =  [NSSet setWithObjects:@"application/json", @"text/json", @"text/javascript",@"text/plain",@"text/html", nil];
        _requestManager.responseSerializer = [AFHTTPResponseSerializer serializer];
    }
    _requestManager.requestSerializer.timeoutInterval = kTimeoutInterval;

    return _requestManager;
}

@end
